package com.si.sea_island.interceptor;


import com.si.sea_island.mapper.VerifyMapper;
import com.si.sea_island.pojo.VerifyDB;
import com.si.sea_island.utils.DateUtils;
import com.si.sea_island.utils.IPUtils;
import com.si.sea_island.utils.JwtTokenUtil;
import io.jsonwebtoken.Claims;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.time.LocalTime;
import java.util.Date;

@Component
public class TokenInterceptor implements HandlerInterceptor {
    private static final Logger log = LoggerFactory.getLogger(TokenInterceptor.class);

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    VerifyMapper verifyMapper;


    //在请求处理之前进行逻辑处理
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

//        // 允许跨域访问的域名：若有端口需写全（协议+域名+端口），若没有端口末尾不用加'/'
//        //        response.setHeader("Access-Control-Allow-Origin", "http://192.168.0.60:8000");
//        response.setHeader("Access-Control-Allow-Origin", "*");
//
//        // 允许前端带认证cookie：启用此项后，上面的域名不能为'*'，必须指定具体的域名，否则浏览器会提示
//        response.setHeader("Access-Control-Allow-Credentials", "true");
//
//        // 提示OPTIONS预检时，后端需要设置的两个常用自定义头
//        response.setHeader("Access-Control-Allow-Headers", "Content-Type,X-Requested-With");

        String companyName = request.getParameter("companyName");
        LocalTime start = LocalTime.now();
        String ip = IPUtils.getIpAddress(request);
        String ipDes = IPUtils.isInternalIp(ip)?"【内网】":"【公网】";
        String reqUrl = request.getRequestURL().toString();
        log.info("Token===="+ip+ipDes+" 请求地址："+reqUrl);
        String token = request.getHeader("token");

        log.info("ip:{}",ip);

        int userId = 0;
        String account = "";
        try{
            Claims tokenClaims = JwtTokenUtil.getClaims(token);
            userId = Integer.parseInt(String.valueOf(tokenClaims.get("userId")));
            account = String.valueOf(tokenClaims.get("accountType"));

            //判断token是否与数据库相同
            VerifyDB verifyDB = null;
            if ("user".equals(account)){
                verifyDB = verifyMapper.getVerifyDB(userId,"0");
            }else if ("admin".equals(account)){
                verifyDB = verifyMapper.getVerifyDB(userId,"1");
            }
            if (!token.equals(verifyDB.getToken())){
                returnJson(response,"{\"code\":-1,\"msg\":\"请重新登录\"}");
                return false;
            }else if (checkTime(verifyDB.getTime())){
                returnJson(response,"{\"code\":-1,\"msg\":\"请重新登录\"}");
                return false;
            }
            //更新token
            if ("user".equals(account)){
                verifyMapper.updateTime(userId, DateUtils.getNowTime(),0);
            }else if ("admin".equals(account)){
                verifyMapper.updateTime(userId, DateUtils.getNowTime(),1);
            }
            return true;
        }catch (Exception e){
            returnJson(response,"{\"code\":-1,\"msg\":\"请重新登录\"}");
            return false;
        }


//        //检测header
//        returnJson(response,"{\"code\":-1,\"msg\":\"请重新登录\"}");
//        return false;//中断对该请求的处理
    }

    /*返回客户端数据*/
    private void returnJson(HttpServletResponse response, String json) throws Exception{
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=utf-8");
        try {
            writer = response.getWriter();
            writer.print(json);

        } catch (IOException e) {
        } finally {
            if (writer != null)
                writer.close();
        }
    }

    private boolean checkTime(String time){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try{
            Date parse = sdf.parse(time);
            Date date = new Date(new Date().getTime()-15*24*60*60*1000);
            if (date.before(parse)){
                return false;
            }
        }catch (Exception e){
            return false;
        }
        return true;
    }


    //在请求处理之后进行逻辑处理，渲染视图等
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    //在请求完成之后进行逻辑处理，如清理资源等
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {



    }
}
